package com.tacuati;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

public class Utils {
	public static String readFileAsString(String filePath) throws IOException, FileNotFoundException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}

	public static java.util.List<File> getFiles(File dir) {
		java.util.List<File> result = new ArrayList<File>();
		File[] filesAndDirs = dir.listFiles();
		if (filesAndDirs != null) {
			java.util.List<File> filesDirs = Arrays.asList(filesAndDirs);
			for (File file : filesDirs) {
				result.add(file);
				if (!file.isFile()) {
					java.util.List<File> deeperList = getFiles(file);
					result.addAll(deeperList);
				}
			}
		}
		return result;
	}

	public static String bytes2hex(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		for (int i = 0; i < bytes.length; i++) {
			int high = ((bytes[i] & 0xf0) >> 4);
			int low = (bytes[i] & 0x0f);
			sb.append(hexChars[high]);
			sb.append(hexChars[low]);
		}
		return sb.toString();
	}

	public static long byteArrayToInteger(byte[] by) {
		long value = 0;
		for (int i = 0; i < by.length; i++) {
			value = (value << 8) + (by[i] & 0xff);
		}
		return value;
	}

	public static String getHash(String path) {
		String hash = "";
		try {
			MessageDigest md;
			md = MessageDigest.getInstance("SHA1");
			hash = "/mnt/us/documents/" + URLDecoder.decode(path.substring(path.indexOf("/documents/") + 11), "UTF-8");
			hash = Utils.bytes2hex(md.digest(hash.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hash;
	}

	public static void writeFile(String path, String text) throws FileNotFoundException {
		PrintWriter out = new PrintWriter(path);
		out.print(text);
		out.close();
	}

	public static void copyFile(String s, String d) throws IOException {
		File sourceFile = new File(s);
		File destFile = new File(d);

		if (!destFile.exists()) {
			destFile.createNewFile();
		}

		FileChannel source = null;
		FileChannel destination = null;
		try {
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();

			long count = 0;
			long size = source.size();
			while ((count += destination.transferFrom(source, 0, size - count)) < size)
				;
		} finally {
			if (source != null) {
				source.close();
			}
			if (destination != null) {
				destination.close();
			}
		}
	}

	public static int compareJsonObjects(JSONObject jsonFile1, JSONObject jsonFile2) {
		int diffs = 0;
		try {
			Iterator it = jsonFile1.keys();
			while (it.hasNext()) {
				String collectionJsonString = it.next().toString();
				
				try {
					jsonFile2.get(collectionJsonString);
				} catch (Exception e){
					diffs++;
					System.out.println("Collection not found: " + collectionJsonString);
					break;					
				}

				String lastAccess1 = ((JSONObject) jsonFile1.get(collectionJsonString)).get("lastAccess").toString();
				String lastAccess2 = ((JSONObject) jsonFile2.get(collectionJsonString)).get("lastAccess").toString();

				if (!lastAccess1.equals(lastAccess2)) {
					System.out.println("Collection lastAccess not equal: " + collectionJsonString);
					diffs++;
				}

				JSONArray items1 = (JSONArray) ((JSONObject) jsonFile1.get(collectionJsonString)).get("items");
				JSONArray items2 = (JSONArray) ((JSONObject) jsonFile2.get(collectionJsonString)).get("items");

				for (int i = 0; i < items1.length(); i++) {
					String i1 = items1.get(i).toString();
					boolean found = false;
					for (int j = 0; j < items2.length(); j++) {
						String i2 = items2.get(j).toString();
						if (i2.equals(i1)) {
							found = true;
							break;
						}
					}
					if (!found) {
						System.out.println("Item " + i1 + " not found at collection: " + collectionJsonString);
						diffs++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return diffs;
	}
}
